package com.mxl;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * @author mxl
 * @description: 文件操作测试
 * @date 2022-02-17 14:14
 */
@Slf4j
public class FileTest {
    public static void main(String[] args) throws IOException {
        String fileName="src/main/java/com/mxl/text.txt";
        //写入信息
        writerFile(fileName,"不错\n很好");
        //读取文件
        ReaderFile(fileName);
    }

    /**
     * 写入文件
     *
     * @param fileName 文件名
     * @param content  文件内容
     */
    public static void writerFile(String fileName, String content) throws IOException {
        FileWriter writer = null;
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            writer = new FileWriter(fileName, true);
            writer.write(content);

        } catch (IOException e) {
            log.error("写入异常" + e.getMessage());
        } finally {
            writer.close();
        }
    }

    /**
     * 读取文件
     *
     * @param fileName 文件名
     * @throws IOException
     */
    private static void ReaderFile(String fileName) throws IOException {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                System.out.println("line " + line + ": " + tempString);
                line++;
            }

        } catch (IOException e) {
            log.error("读取异常" + e.getMessage());
        } finally {
            if (null != reader) {
                reader.close();
            }
        }
    }
}
